﻿using AdminSystem.Application;
using AdminSystem.Domain;
using AdminSystem.Repositories;
using AdminSystem.WebApi.MedialRs.Commands.TracebilityCommand;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NPOI.SS.UserModel;
using NPOI.XSSF.Streaming;
using System.Collections.Generic;

namespace AdminSystem.WebApi.MedialRs.CommandHandlers.Tracebilitys
{
    public class TracebilityExportCommandHandler : IRequestHandler<TracebilityExportCommand, ApiResult<object>>
    {
        public TracebilityExportCommandHandler(IRepository<Tracebility> repository)
        {
            Repository = repository;
        }

        public IRepository<Tracebility> Repository { get; }

        public Task<ApiResult<object>> Handle(TracebilityExportCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            result.statusCode = StatusCode.Success;
            result.Message = "导出成功";
            var info = Repository.GetAll().Result;
            IWorkbook workbook = new SXSSFWorkbook();
            ISheet sheet = workbook.GetSheet("列表显示");
            IRow row = sheet.CreateRow(0);
            row.GetCell(0).SetCellValue("溯源编号");
            row.GetCell(1).SetCellValue("商品编号");
            row.GetCell(2).SetCellValue("生产批次");
            row.GetCell(3).SetCellValue("保质期");
            row.GetCell(4).SetCellValue("生产许可证");
            row.GetCell(5).SetCellValue("生产企业");

            for (int i = 0; i < info.Count; i++)
            {
                var newrow = sheet.CreateRow(1 + 1);
                newrow.GetCell(0).SetCellValue(info[i].TraceabilityId);
                newrow.GetCell(1).SetCellValue(info[i].ShoppId);
                newrow.GetCell(2).SetCellValue(info[i].ProBatch);
                newrow.GetCell(3).SetCellValue(info[i].ShelfLife);
                newrow.GetCell(4).SetCellValue(info[i].ProLicense);
                newrow.GetCell(5).SetCellValue(info[i].Manufacturers);
            }
            using (FileStream fs = new FileStream(request.file, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);
            }
            return Task.FromResult(result);
        }
    }
}
